Public Class OrderInput
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents valsValidationSummary As System.Web.UI.WebControls.ValidationSummary
    Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button
    Protected WithEvents btnCancel As System.Web.UI.WebControls.Button
    Protected WithEvents lblErr As System.Web.UI.WebControls.Label
    Protected WithEvents btnReset As System.Web.UI.WebControls.Button
    Protected WithEvents ddlOrderType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtOrderNo As System.Web.UI.WebControls.TextBox
    Protected WithEvents reqvOrderNo As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtCustomerName As System.Web.UI.WebControls.TextBox
    Protected WithEvents reqvCustomerName As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtDestinationPort As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtSortRef As System.Web.UI.WebControls.TextBox
    Protected WithEvents reqvSortRef As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtSortRange As System.Web.UI.WebControls.TextBox
    Protected WithEvents radETAAsap As System.Web.UI.WebControls.RadioButton
    Protected WithEvents radETABefore As System.Web.UI.WebControls.RadioButton
    Protected WithEvents txtETABefore As System.Web.UI.WebControls.TextBox
    Protected WithEvents radETAAfter As System.Web.UI.WebControls.RadioButton
    Protected WithEvents txtETAAfter As System.Web.UI.WebControls.TextBox
    Protected WithEvents radETABetween As System.Web.UI.WebControls.RadioButton
    Protected WithEvents txtETAFrom As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtETATo As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtNoContainers As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlContainerType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents comvContainerNo As System.Web.UI.WebControls.CompareValidator
    Protected WithEvents ddlPackingType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlShippingType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtOrderDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents reqvOrderDate As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtOrderBy As System.Web.UI.WebControls.TextBox
    Protected WithEvents reqvOrderBy As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtGeneralShippingInstructions As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnAddOI As System.Web.UI.WebControls.ImageButton
    Protected WithEvents dgItems As System.Web.UI.WebControls.DataGrid
    Protected WithEvents hidCustomerID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hidContactID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents btnRemoveOI As System.Web.UI.WebControls.ImageButton
    Protected WithEvents txtSupplierCode As System.Web.UI.WebControls.TextBox
    Protected WithEvents reqvSupplierCode As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents hidDestinationPortID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hidSupplierID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hidSortRefID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents hidSortRangeID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents regvOrderNo As System.Web.UI.WebControls.RegularExpressionValidator
    Protected WithEvents regvSI As System.Web.UI.WebControls.RegularExpressionValidator
    Protected WithEvents ddlOrderItemType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents trSortRange As System.Web.UI.HtmlControls.HtmlTableRow
    Protected WithEvents txtSortRef2 As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents hidSortRefID2 As System.Web.UI.HtmlControls.HtmlInputHidden

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
    Protected WithEvents Header1 As Header

    Private Const ORDER_LIST_URL As String = "/Internal/OrderList.aspx"
    Private Const ORDER_INPUT_URL As String = "/Internal/OrderInput.aspx"
    Public Const ORDER_INPUT_PAGEBO_SESSION_NAME As String = "MIMS_WRS.Web.OrderInput.PageBO"

#Region "   Properties"
    Protected Property PageBO() As COrder
        Get
            If IsNothing(Session(OrderInput.ORDER_INPUT_PAGEBO_SESSION_NAME)) Then
                Throw New ApplicationException("Session expried. Please re-login")
            End If
            Return CType(Session(ORDER_INPUT_PAGEBO_SESSION_NAME), COrder)
        End Get
        Set(ByVal Value As COrder)
            Session(ORDER_INPUT_PAGEBO_SESSION_NAME) = Value
        End Set
    End Property

    Protected ReadOnly Property FormattedCurrentDate() As String
        Get
            Return "'" + FormatDate(System.DateTime.Now) + "'"
        End Get
    End Property

    Protected ReadOnly Property OrderID() As Integer
        Get
            Try
                If IsNothing(Request.QueryString("id")) Then
                    Return 0
                End If

                Dim id As Integer
                id = CInt(Request.QueryString("id"))

                If id < 0 Then
                    Throw New Exception
                End If

                Return id
            Catch ex As Exception
                Throw New ApplicationException("Invalid or missing parameter", ex)
            End Try
        End Get
    End Property
#End Region

#Region "   Private functions"
    Private Sub InitControls()
        Me.ddlContainerType.DataSource = EnumToList(GetType(EContainerType))
        Me.ddlContainerType.DataTextField = "Text"
        Me.ddlContainerType.DataValueField = "Value"

        Me.ddlOrderType.DataSource = EnumToList(GetType(EOrderType))
        Me.ddlOrderType.DataTextField = "Text"
        Me.ddlOrderType.DataValueField = "Value"

        Me.ddlPackingType.DataSource = EnumToList(GetType(EPackingType))
        Me.ddlPackingType.DataTextField = "Text"
        Me.ddlPackingType.DataValueField = "Value"

        Me.ddlShippingType.DataSource = EnumToList(GetType(EShippingType))
        Me.ddlShippingType.DataTextField = "Text"
        Me.ddlShippingType.DataValueField = "Value"

        Me.ddlOrderItemType.DataSource = EnumToList(GetType(EOrderItemType))
        Me.ddlOrderItemType.DataTextField = "Text"
        Me.ddlOrderItemType.DataValueField = "Value"

        Me.DataBind()
    End Sub

    Private Sub UpdateData(ByVal bSave As Boolean)
        If bSave Then
            PageBO.DestinationPortLkdID = CInt(Me.hidDestinationPortID.Value)
            PageBO.SortRangeLkdID = CInt(Me.hidSortRangeID.Value)
            PageBO.SortReferenceLkdID = CInt(Me.hidSortRefID.Value)
            PageBO.SortReference2LkdID = CInt(Me.hidSortRefID2.Value)
            PageBO.SupplierLkdID = CInt(Me.hidSupplierID.Value)
            PageBO.ContainerType = CByte(Me.ddlContainerType.SelectedIndex)
            PageBO.OrderType = CByte(Me.ddlOrderType.SelectedIndex)
            PageBO.PackingType = CByte(Me.ddlPackingType.SelectedIndex)
            PageBO.ShippingType = CByte(Me.ddlShippingType.SelectedIndex)

            ' bulk Order also has order item type = Independent PO
            If CType(PageBO.OrderType, EOrderType) = EOrderType.Bulk_Order Then
                PageBO.OrderItemType = EOrderItemType.Independent_PO
            Else
                PageBO.OrderItemType = CByte(Me.ddlOrderItemType.SelectedItem.Value)
            End If

            PageBO.CustomerID = CInt(hidCustomerID.Value)
            PageBO.OrderByCustomerID = CInt(hidContactID.Value)

            If radETAAfter.Checked Then
                PageBO.RequestedETA = ERequestedETAType.After
                PageBO.ETADate1 = CDate(Me.txtETAAfter.Text)
            End If

            If radETAAsap.Checked Then
                PageBO.RequestedETA = ERequestedETAType.As_soon_as_possible
            End If

            If radETABefore.Checked Then
                PageBO.RequestedETA = ERequestedETAType.Before
                PageBO.ETADate1 = CDate(Me.txtETABefore.Text)
            End If

            If radETABetween.Checked Then
                PageBO.RequestedETA = ERequestedETAType.Between
                PageBO.ETADate1 = CDate(Me.txtETAFrom.Text)
                PageBO.ETADate2 = CDate(Me.txtETATo.Text)
            End If

            PageBO.OrderNumber = txtOrderNo.Text
            PageBO.Containers = CInt(txtNoContainers.Text)
            PageBO.OrderDate = CDate(txtOrderDate.Text)
            PageBO.ShippingInstructions = txtGeneralShippingInstructions.Text
        Else
            Me.hidSupplierID.Value = PageBO.SupplierLkdID.ToString
            Me.hidSortRefID.Value = PageBO.SortReferenceLkdID.ToString
            Me.hidSortRefID2.Value = PageBO.SortReference2LkdID.ToString
            Me.hidSortRangeID.Value = PageBO.SortRangeLkdID.ToString
            Me.hidDestinationPortID.Value = PageBO.DestinationPortLkdID.ToString

            Me.ddlContainerType.SelectedIndex = PageBO.ContainerType
            Me.ddlOrderType.SelectedIndex = PageBO.OrderType
            Me.ddlPackingType.SelectedIndex = PageBO.PackingType
            Me.ddlShippingType.SelectedIndex = PageBO.ShippingType
            Me.ddlOrderItemType.SelectedIndex = Me.ddlOrderItemType.Items.IndexOf(Me.ddlOrderItemType.Items.FindByValue(PageBO.OrderItemType.ToString()))
            Me.hidCustomerID.Value = PageBO.CustomerID.ToString
            Me.hidContactID.Value = PageBO.OrderByCustomerID.ToString

            Me.radETAAsap.Checked = CType(PageBO.RequestedETA, ERequestedETAType) = ERequestedETAType.As_soon_as_possible
            Me.radETAAfter.Checked = CType(PageBO.RequestedETA, ERequestedETAType) = ERequestedETAType.After
            Me.radETABefore.Checked = CType(PageBO.RequestedETA, ERequestedETAType) = ERequestedETAType.Before
            Me.radETABetween.Checked = CType(PageBO.RequestedETA, ERequestedETAType) = ERequestedETAType.Between

            Select Case CType(PageBO.RequestedETA, ERequestedETAType)
                Case ERequestedETAType.After
                    Me.txtETAAfter.Text = FormatDate(PageBO.ETADate1)
                Case ERequestedETAType.As_soon_as_possible
                Case ERequestedETAType.Before
                    Me.txtETABefore.Text = FormatDate(PageBO.ETADate1)
                Case ERequestedETAType.Between
                    Me.txtETAFrom.Text = FormatDate(PageBO.ETADate1)
                    Me.txtETATo.Text = FormatDate(PageBO.ETADate2)
            End Select

            txtOrderNo.Text = PageBO.OrderNumber
            txtNoContainers.Text = PageBO.Containers.ToString
            txtOrderDate.Text = FormatDate(PageBO.OrderDate)
            txtGeneralShippingInstructions.Text = PageBO.ShippingInstructions
        End If
    End Sub

    Private Sub BindGrid()
        Me.dgItems.DataSource = PageBO.OrderItems
        Me.dgItems.DataBind()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not Page.IsPostBack Then
            Security.InternalAndAdminOnly()

            Header1.NavigationBar.Add("Back to Order List", AppRoot() & Me.ORDER_LIST_URL)

            If IsNothing(Request.QueryString("back")) Then

                Dim obj As New COrder
                obj.Init()
                'If OrderID > 0 Then
                '    Try
                '        obj.Load(OrderID)
                '    Catch ex As Exception
                '        Throw New ApplicationException("Failed to load order data", ex)
                '    End Try
                'Else
                '    obj.Init()
                'End If

                PageBO = obj
            End If

            InitControls()

            UpdateData(False)

            Me.BindGrid()
        End If

        ' a replacement for SmartNavigation
        Me.RegisterHiddenField("txtPos", CStr(IIf(Request("txtPos") = "", "0", Request("txtPos"))))
    End Sub

#Region "   Order's data function"
    Protected Function GetCustomerName() As String
        Return CUser.GetName(PageBO.CustomerID)
    End Function

    Protected Function GetContactName() As String
        If PageBO.CustomerID > 0 AndAlso PageBO.OrderByCustomerID > 0 Then
            Dim objCusContact As New CCustomerContact
            Try
                objCusContact.Load(PageBO.OrderByCustomerID)
            Catch ex As Exception
                Throw New ApplicationException("Can not load customer name", ex)
            End Try

            'check for data integrity
            If objCusContact.CustomerID <> PageBO.CustomerID Then
                Throw New ApplicationException("Order data invalid, please check for customer id and customer's contact id")
            End If

            Return objCusContact.ContactName
        Else
            Return Nothing
        End If
    End Function
#End Region

#Region "   Button's event handler"
    Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Try
            UpdateData(True)

            'checking input data
            Dim objCC As New CCustomerContact
            objCC.Load(PageBO.OrderByCustomerID)

            If objCC.CustomerID <> PageBO.CustomerID Then
                Me.lblErr.Text = String.Format("The contactor <i>{0}</i> is not <i>{1}'s</i> contactor.<br>Please select another one.", Me.txtOrderBy.Text, Me.txtCustomerName.Text)
                Exit Sub
            End If

            'From now on, the user will be forwarded to the confirm page.
            'On that page, he has got 2 options, either commit his action 
            'or cancel then go back to the input form for correcting any spelling mistakes.
            Response.Redirect("OrderConfirm.aspx")

            'PageBO.Save()
            'Response.Redirect(AppRoot() & Me.ORDER_LIST_URL)
        Catch ex As DataEntryException
            lblErr.Text = "Order number already exists. Please enter another one."
        Catch ex As Exception
            lblErr.Text = ex.Message
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect(AppRoot() & Me.ORDER_LIST_URL)
    End Sub

    Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
        Response.Redirect(AppRoot() & Me.ORDER_INPUT_URL)
    End Sub

    Private Overloads Sub btnAddOI_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAddOI.Click
        ' Hoa added : save order data to pageBO
        Me.UpdateData(True)

        Me.BindGrid()
    End Sub

    Private Overloads Sub btnRemoveOI_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnRemoveOI.Click
        ' Hoa added : save order data to pageBO
        Me.UpdateData(True)

        Dim dgi As DataGridItem
        For Each dgi In Me.dgItems.Items
            Dim chk As HtmlInputCheckBox
            chk = CType(dgi.Cells(0).FindControl("chkSelection"), HtmlInputCheckBox)
            If chk.Checked Then
                Try
                    PageBO.RemoveOrderItem(CInt(chk.Value))
                Catch ex As Exception
                    Throw New ApplicationException("Failed to delete item " & chk.Value, ex)
                End Try
            End If
        Next
        Me.BindGrid()
    End Sub

#End Region

    Protected Sub btnEdit_OnClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ' Hoa added : load order data from pageBO
        Me.UpdateData(False)

        Me.BindGrid()
        ddlOrderItemType.SelectedIndex = PageBO.OrderItemType
    End Sub

    Protected Function GetEditIndex(ByVal container As Object) As String
        Dim dgi As DataGridItem = CType(container, DataGridItem)
        Return String.Format("if (!btnEdit_onclick({0})) return false;", dgi.ItemIndex)
    End Function
End Class
